package Opa

import (
	"fmt"
	v1 "gitee/kubehark/kubehark-operator/api/kubehark/v1"
	"github.com/gin-gonic/gin"
	"github.com/mitchellh/mapstructure"
	"github.com/sirupsen/logrus"
	"kubehark/kubehark-framwork/pkg/Data/DataSourceCrd"
	"kubehark/kubehark-framwork/pkg/Plugin/Plugins"
	"kubehark/kubehark-framwork/pkg/opa"
	"kubehark/kubehark-framwork/pkg/response"
)

type OpaPlugin struct {
	Config OpaConfig
}

type OpaConfig struct {
	RegoModelPath  []string `json:"regomodelpath"`
	UserRolesUrl    string `json:"userrolesurl"`
	RoleGrantsUrl   string `json:"rolegrantsurl"`
}

func (this *OpaPlugin) SetConfigFromInterface(data interface{}) Plugins.PluginInterface {
	theInforMap := data.(map[string]interface{})
	var Config OpaConfig
	if err := mapstructure.Decode(theInforMap, &Config); err != nil {
		logrus.Error(err.Error())
	}
	fmt.Println(99)
	fmt.Println(Config.UserRolesUrl)
	fmt.Println(Config.RoleGrantsUrl)
	return &OpaPlugin{
		Config: Config,
	}

}

func (this *OpaPlugin) RunPlugin(c *gin.Context) error {
	clusterID := c.Param("clusterID")
	data,exit,err:=DataSourceCrd.GetDataFromInformer(DataSourceCrd.Credential,clusterID)
	if err!= nil{
		return err
	}
	if !exit{
		response.GInFailed(c,fmt.Sprintf("登录失败 该(%s)集群不存在 ",clusterID))
		c.Abort()
		return err
	}
	crd := data.(*v1.Credential)


	result,err :=opa.Opa(crd.Labels,
		c.Request.Method,
		c.GetString("user"),
		this.Config.RegoModelPath,
		this.Config.RoleGrantsUrl,
		this.Config.UserRolesUrl,
	)
	if err!=nil{
		response.GInFailed(c,err.Error())
		c.Abort()
		return err
	}
	if len(result) != 0 && result[0].Bindings["allow"].(bool){
		//c.Next()
		return  nil
	}else {
		//fmt.Println("登录失败")
		//fmt.Println("%v ",result)
		response.OpaFail(c,200,fmt.Sprintf("登录 %s 失败  用户名%s没有权限操作该集群", clusterID, c.GetString("user")))
		c.Abort()
		return nil
	}
	return nil
}
